﻿using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using System.Data;
using BEGDC.Utility.NHibernate;
using Castle.Services.Transaction;
using System.Collections;
using System.Xml;
using Castle.Facilities.NHibernateIntegration;

namespace BEGDC.PreContract.BLL
{
	public partial class Employee: IEmployee
	{

        public enum ASBorLucent
        {
            ASB = 0,
            Lucent = 1,
            All = 2
        }

        //Get by id
        [Transaction(TransactionMode.Requires)]
        public BEGDC.PreContract.DAL.Employee GetEmployeeByCILAccount(string cilAccount)
        {
            BEGDC.PreContract.DAL.Employee employee = BEGDC.PreContract.DAL.Employee.FindFirst(new NHibernate.Expression.EqExpression(BEGDC.PreContract.DAL.Employee.CONST_CILAccount, cilAccount));

            return employee;
        }

        //Get by id
        [Transaction(TransactionMode.Requires)]
        public BEGDC.PreContract.DAL.Employee GetEmployeeByADAccount(string adAccount)
        {
            BEGDC.PreContract.DAL.Employee employee = BEGDC.PreContract.DAL.Employee.FindFirst(new NHibernate.Expression.EqExpression(BEGDC.PreContract.DAL.Employee.CONST_ADAccount, adAccount));

            return employee;
        }

        //Get BD
        [Transaction(TransactionMode.Requires)]
        public DataTable GetEmployeeBD()
        {
            using (ISession session = factory.OpenSession())
            {
                string strSql = "SELECT distinct BD FROM Employee";
                DataTable dtSearch = DAO.ExecuteDataTable(session, strSql);

                return dtSearch;
            }
        }

        public string GetDataPermission(int employeeId)
        {
            string strRet = string.Empty;
            string strRet_Empty = " 1=2 "; //没有数据

            BEGDC.PreContract.DAL.Employee employee = this.GetEmployee(employeeId);

            if (employee == null)
                return strRet_Empty;

            //Role
            BEGDC.PreContract.BLL.IUserRole userroleService = (BEGDC.PreContract.BLL.IUserRole)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_UserRole_Service];

            //判断是否是Administrator 如果是则有所有数据. 如果不是要判断CAT, Province, DB, ASB or Lucent
            if (!userroleService.IsAdmin(employee.EmployeeID)) 
            {
                //ASBOrLucent
                if (employee.ASBOrLucent != (int)ASBorLucent.All)
                {
                    strRet += string.Format(" ASBOrLucent = {0} AND ", employee.ASBOrLucent.ToString()) ;
                }


                //CAT
                BEGDC.PreContract.BLL.ICATAssignment catservice = (BEGDC.PreContract.BLL.ICATAssignment)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_CATAssignment_Service];
                System.Data.DataTable dtCAT = catservice.GetCATAssignment_DataTable(string.Format(" EmployeeID = {0} ", employee.EmployeeID.ToString()));

                string strCAT = string.Empty;
                foreach (System.Data.DataRow dr in dtCAT.Rows)
                {
                    strCAT += dr[BEGDC.PreContract.DAL.CATAssignment.CONST_CATID].ToString() + ",";
                }

                if (strCAT != string.Empty)
                {
                    strCAT = strCAT.Substring(0, strCAT.Length - 1);

                    strRet += string.Format(" CATID in ({0}) AND ", strCAT);
                }
                else
                {
                    return strRet_Empty;
                }

                //BD
                BEGDC.PreContract.BLL.IBDAssignment bdservice = (BEGDC.PreContract.BLL.IBDAssignment)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_BDAssignment_Service];
                System.Data.DataTable dtBD = bdservice.GetBDAssignment_DataTable(string.Format(" EmployeeID = {0} ", employee.EmployeeID.ToString()));

                string strBD = string.Empty;
                foreach (System.Data.DataRow dr in dtBD.Rows)
                {
                    strBD += dr[BEGDC.PreContract.DAL.BDAssignment.CONST_BDID].ToString() + ",";
                }

                if (strBD != string.Empty)
                {
                    strBD = strBD.Substring(0, strBD.Length - 1);

                    strRet += string.Format(" BDID in ({0}) AND ", strBD);
                }
                else
                {
                    return strRet_Empty;
                }

                //Province
                BEGDC.PreContract.BLL.IProvinceAssignment provinceservice = (BEGDC.PreContract.BLL.IProvinceAssignment)BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.PreContract.BLL.Services.CONST_ProvinceAssignment_Service];
                System.Data.DataTable dtProvince = provinceservice.GetProvinceAssignment_DataTable(string.Format(" EmployeeID = {0} ", employee.EmployeeID.ToString()));

                string strProvince = string.Empty;
                foreach (System.Data.DataRow dr in dtProvince.Rows)
                {
                    strProvince += dr[BEGDC.PreContract.DAL.ProvinceAssignment.CONST_ProvinceID].ToString() + ",";
                }

                if (strProvince != string.Empty)
                {
                    strProvince = strProvince.Substring(0, strProvince.Length - 1);

                    strRet += string.Format(" ProvinceID in ({0}) AND ", strProvince);
                }
                else
                {
                    return strRet_Empty;
                }

            }

            if (strRet.EndsWith("AND "))
                strRet = strRet.Substring(0, strRet.Length - 4);


            return strRet;
        }

        //Joan.Lu 2008-09-25
        //Check if the user has asb or lucent permission
        public bool CheckEntityPermission(long employeeID, string asbOrLucent)
        {

            using (ISession session = factory.OpenSession())
            {
                string strSql = "SELECT EmployeeID FROM dbo.Employee WHERE EmployeeID=" +employeeID.ToString() + " AND (ASBOrLucent=2 OR ASBOrLucent= " + asbOrLucent  + ")";
                DataTable dtSearch = DAO.ExecuteDataTable(session, strSql);
                if (dtSearch.Rows.Count > 0)
                    return true;
                else
                    return false;
            }
                    
        }
        public string GetEntityPermission(long employeeID)
        {
            using (ISession session = factory.OpenSession())
            {
                string strSql = "SELECT a.EmployeeID,a.ASBOrLucent,c.RoleID FROM dbo.Employee a INNER JOIN dbo.UserRole b ON a.EmployeeID=b.EmployeeID LEFT OUTER JOIN  (SELECT RoleID FROM dbo.Role WHERE RoleName='Admin') c ON b.RoleID=c.RoleID WHERE a.EmployeeID=" + employeeID.ToString();
                DataTable dtSearch = DAO.ExecuteDataTable(session, strSql);
                if (dtSearch.Rows.Count > 0)
                {
                    if (dtSearch.Rows[0]["RoleID"] == DBNull.Value)
                        return dtSearch.Rows[0]["ASBOrLucent"].ToString();
                    else
                        return "2"; //ALL
                }
                else
                    return string.Empty;

            }
        }
        //Check if the user is allowed to download saved history reports
        public bool AllowedDownload(long employeeID)
        {
            using (ISession session = factory.OpenSession())
            {
                if (!CheckReportPermission(employeeID))
                    return false;

                string strSql = "SELECT EmployeeID FROM dbo.Employee WHERE EmployeeID=" + employeeID.ToString() + " AND DownloadAllowed=1";
                DataTable dtSearch = DAO.ExecuteDataTable(session, strSql);
                if (dtSearch.Rows.Count > 0)
                    return true;
                else
                    return false;
            }
            
        }
        //Check if the user is allowed view reports
        public bool CheckReportPermission(long employeeID)
        {

            using (ISession session = factory.OpenSession())
            {
                string strSql = "SELECT a.* FROM dbo.UserRole a INNER JOIN dbo.Role b ON a.RoleID=b.RoleID WHERE (b.RoleName='Admin' OR b.RoleName='Editer'OR b.RoleName='Viewer') AND  a.EmployeeID=" + employeeID.ToString();

                DataTable dt = DAO.ExecuteDataTable(session, strSql);

                if (dt.Rows.Count > 0)
                    return true;
                else
                    return false;
            }       
        }

        /// <summary>
        /// Query Employees by PCAT and role
        /// </summary>
        /// <param name="filter">Query requirements</param>
        /// <returns>Employee list</returns>
        [Transaction(TransactionMode.Requires)]
        public DataTable GetEmployeesByPCATOrRole_DataTable(string filter)
        {
            using (ISession session = factory.OpenSession())
            {
                string strSql = "select Distinct em.* from Employee em ";
                strSql += "left join CATAssignment ca on ca.EmployeeID = em.EMployeeID ";
                strSql += "left join ProvinceAssignment pa on pa.EmployeeID = em.EMployeeID ";
                strSql += "left join UserRole ur on ur.EmployeeID = em.EMployeeID";
                if (filter.Trim() != string.Empty)
                    strSql += " WHERE " + filter;
                DataTable dtSearch = DAO.ExecuteDataTable(session, strSql);

                return dtSearch;
            }
        }
        //end
	}
}



